package com.lagou.firststage.fourmode;

/**
 * @author：dingyuan
 * @date：Created in 2022/1/15 22:58
 * @description：作业三测试类
 * @version: 1.0
 */
public class WorkThreeTest {
    public static void main(String[] args){

        // 火车卖票，共100张票
        Ticket ticket = new Ticket(100);

        // 卖票线程1
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (ticket) {
                        if (ticket.getNum() > 0) {
                            ticket.setNum((ticket.getNum() - 1));
                            System.out.println(Thread.currentThread().getName() + "成功卖出一张票，剩余" + ticket.getNum() + "票");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        },"Thread1");

        // 卖票线程2
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (ticket) {
                        if (ticket.getNum() > 0) {
                            ticket.setNum((ticket.getNum() - 1));
                            System.out.println(Thread.currentThread().getName() + "成功卖出一张票，剩余" + ticket.getNum() + "票");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        },"Thread2");

        // 卖票线程3
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (ticket) {
                        if (ticket.getNum() > 0) {
                            ticket.setNum((ticket.getNum() - 1));
                            System.out.println(Thread.currentThread().getName() + "成功卖出一张票，剩余" + ticket.getNum() + "票");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            break;
                        }
                    }
                }
            }
        },"Thread3");

        thread1.start();
        thread2.start();
        thread3.start();
    }
}
